import React from "react";
import { Menu } from "antd";
import { Link, useLocation } from "react-router-dom";
import { useSelector } from "react-redux";
import * as AntdIcons from "@ant-design/icons";

const SideMenu = ({ theme }) => {
  // 从Redux store中获取菜单数据
  const menus = useSelector((state) => state.user.menus);
  // 获取当前路由位置
  const location = useLocation();

  // 根据图标名称获取对应的Antd图标组件
  const getIcon = (iconName) => {
    const AntdIcon = AntdIcons[iconName];
    return AntdIcon ? React.createElement(AntdIcon) : null;
  };

  // 将菜单数据转换为Antd Menu所需的格式，并过滤掉isHidden为true的项
  const convertMenuToItems = (menuArray) => {
    return menuArray
      .filter(menu => !menu.isHidden) // 过滤掉isHidden为true的菜单项
      .map((menu) => ({
        key: menu.path,
        icon: getIcon(menu.icon),
        label: menu.isRoute ? (
          <Link to={menu.path}>{menu.menuName}</Link>
        ) : (
          menu.menuName
        ),
        children:
          menu.children && menu.children.length > 0
            ? convertMenuToItems(menu.children) // 递归处理子菜单
            : undefined,
      }));
  };

  // 默认的首页菜单项
  const defaultHomeMenuItem = {
    key: "/home",
    icon: getIcon("HomeOutlined"),
    label: <Link to="/home">首页</Link>,
  };

  // 组合默认首页和其他菜单项
  const menuItems = [defaultHomeMenuItem, ...convertMenuToItems(menus)];

  // 查找当前路径对应的所有父级菜单，用于自动展开菜单
  const findOpenKeys = (path) => {
    const result = [];
    const findKeys = (items, parentKey = "") => {
      items.forEach((item) => {
        if (path.startsWith(item.key)) {
          result.push(item.key);
          if (item.children) {
            findKeys(item.children, item.key);
          }
        }
      });
    };
    findKeys(menuItems);
    return result;
  };

  return (
    <Menu
      theme={theme}
      mode="inline"
      selectedKeys={[location.pathname]} // 设置当前选中的菜单项
      defaultOpenKeys={findOpenKeys(location.pathname)} // 设置默认展开的子菜单
      items={menuItems}
    />
  );
};

export default SideMenu;